<template>
  <div class="new_consensus bg-gray">

    <div class="bg-white">
      <div class="w1200">
        <BackBar :backTitle="$t('nav.consensus')"></BackBar>
        <h3 class="title">{{$t('newConsensus.newConsensus0')}}</h3>
      </div>
    </div>

    <div class="w1200 bg-white mt_20">
      <el-form :model="createrForm" :rules="createrRules" ref="createrForm">
        <el-form-item :label="$t('newAddress.newAddress12')">
          <el-input v-model.trim="addressInfo.address" disabled></el-input>
        </el-form-item>
        <el-form-item :label="$t('public.rewardAddress')" prop="rewardAddress">
          <el-input v-model.trim="createrForm.rewardAddress" maxlength="50" disabled></el-input>
        </el-form-item>
        <el-form-item :label="$t('nodeType.3')" prop="amount">
          <span class="balance font12 fr">{{$t('consensus.consensus2')}}: {{balanceInfo.balance/1000000}}</span>
          <el-input v-model.trim="createrForm.amount">
          </el-input>
        </el-form-item>
        <el-form-item class="form-next">
          <!-- <el-button type="success" @click="submitForm('createrForm')" >{{$t('password.password3')}}</el-button> -->
          <el-button type="success" @click="confiremSubmit" >{{$t('password.password3')}}</el-button>
        </el-form-item>
      </el-form>
    </div>
    <Password ref="password" @passwordSubmit="passSubmit"></Password>
    <el-dialog :title="$t('newConsensus.newConsensus1')" :visible.sync="newConsensusVisible" width="40rem"
               class="confirm-dialog">
      <div class="bg-white">
        <div class="div-data">
          <p>{{$t('public.createAddress')}}:&nbsp;</p>
          <label>{{addressInfo.address}}</label>
        </div>
        <div class="div-data">
          <p>{{$t('public.rewardAddress')}}:&nbsp;</p>
          <label>{{createrForm.rewardAddress}}</label>
        </div>
        <div class="div-data">
          <p>{{$t('public.packingAddress')}}:&nbsp;</p>
          <label>{{createrForm.blockAddress}}</label>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="newConsensusVisible = false">{{$t('password.password2')}}</el-button>
        <el-button type="success" @click="confiremSubmit">{{$t('transfer.transfer8')}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  // import nuls from 'nuls-sdk-js'
  import {
    commitData
  } from '@/api/requestData'
  import {addressInfo, getRamNumber, passwordVerification} from '@/api/util'
  import Password from '@/components/PasswordBar'
  import BackBar from '@/components/BackBar'

  export default {
    data() {
      let checkAmount = (rule, value, callback) => {
        let re = /^\d+(?=\.{0,1}\d+$|$)/;
        let res = /^\d{1,8}(\.\d{1,8})?$/;
        let balance = this.balanceInfo.balance - value * 1000000;
        if (!value) {
          return callback(new Error(this.$t('newConsensus.newConsensus5')));
        } else if (!re.exec(value) || !res.exec(value)) {
          callback(new Error(this.$t('newConsensus.newConsensus6')));
        } else if (balance < 0.001) {
          callback(new Error(this.$t('newConsensus.newConsensus7')));
        } else {
          callback();
        }
      };
      return {
        addressInfo: {},//账户信息
        balanceInfo: {},//账户余额信息
        agentAsset: JSON.parse(sessionStorage.getItem('info')),//pocm合约单位等信息
        //创建节点表单
        createrForm: {
          rewardAddress: '',
          blockAddress: '',
          amount: '',
          rate: '',
        },
        createrRules: {
          amount: [
            {validator: checkAmount, trigger: ['blur', 'change']}
          ],
        },
        newConsensusVisible: false,//创建节点确认弹框
        getNewConsensusRandomString: '',
        sendNewConsensusRandomString: '',
      };
    },
    created() {
      this.addressInfo = addressInfo(1);
      setInterval(() => {
        this.addressInfo = addressInfo(1);
      }, 500);

      this.createrForm.rewardAddress =  this.$route.query.addressp
    },
    mounted() {
      setTimeout(() => {
        this.getAddressInfoByNode(this.addressInfo.address);
      }, 600);
    },
    watch: {
      addressInfo(val, old) {
        if (val) {
          if (val.address !== old.address && old.address) {
            this.getAddressInfoByNode(this.addressInfo.address);
          }
        }
      }
    },
    components: {
      Password,
      BackBar,
    },
    methods: {

      /**
       * 创建节点提交
       * @param formName
       **/
      async submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.newConsensusVisible = true;
          } else {
            return false;
          }
        });
      },

      /**
       * 获取账户余额
       * @param assetChainId
       * @param assetId
       * @param address
       **/
      async getAddressInfoByNode(address){
        var params = {
            address: address,
            visible: true
        }
        await this.$post('/wallet/getaccount', 'getAccountLedgerList', params, 'Home')
          .then((response) => {
            // console.log('地址账户余额信息',response);
            this.balanceInfo.balance = response.balance;
          })
          .catch((error) => {
            this.$message({message: this.$t('public.err2') + error, type: 'error', duration: 1000});
          })
      },


      /**
       *  确定框确定提交
       **/
      async confiremSubmit() {
        if (this.addressInfo.aesPri === '') {
          this.getNewConsensusRandomString = await getRamNumber(16);
          this.sendNewConsensusRandomString = await getRamNumber(16);
          let assembleHex = await this.newConsensusAssemble();
          if (!assembleHex.success) {
            this.$message({message: this.$t('tips.tips3'), type: 'error', duration: 3000});
            return;
          }
          let commitDatas = await commitData(this.getNewConsensusRandomString, this.sendNewConsensusRandomString,this.addressInfo.address,assembleHex.data);
          if (!commitDatas.success) {
            this.$message({
              message: this.$t('tips.tips4') + JSON.stringify(commitDatas.data),
              type: 'error',
              duration: 3000
            });
            return;
          }
          this.$refs.password.showScan(commitDatas.data.txInfo, commitDatas.data.assembleHex);
        } else {
          this.$refs.password.showPassword(true);
        }
      },

      /**
       *  获取密码框的密码
       * @param password
       **/
      async passSubmit(password) {
        let passwordInfo = await passwordVerification(this.addressInfo, this.$md5(password));
        if (passwordInfo.success) {
          console.log('密码正确')
          
          const params = {
              password: this.$md5(password),
              delegate_address: this.createrForm.rewardAddress,
              delegate_count: this.createrForm.amount * 1000000,
              owner_address: this.addressInfo.address,
              visible: "true"
          }
          console.log(params)
          await this.$post('/wallet/delegateaccount', 'passSubmit', params)
              .then(response => {
                  console.log(response)
                  if (response.result && response.result  == true) {
                      this.$router.push('/consensus');
                  } else {
                      console.log('失败')
                  }
              })
              .catch(error => {
                  console.log(error);
              });

        } else {
          this.$message({message: this.$t('address.address13'), type: 'error', duration: 1000});
        }
      },


    }
  }
</script>

<style lang="less">
  @import "./../../assets/css/style";

  .new_consensus {
    .mt_20 {
      border: @BD1;
      .el-form {
        width: 600px;
        margin: 50px auto;
        .el-form-item {
          .el-form-item__content {
            .el-select {
              width: 100%;
              .el-input__inner {
                width: 100%;
              }
            }
          }
        }
      }
    }

  }
</style>
